import logging

import allure
import jsonpath
import pymysql

from config.config import *


def assert_http_utils(case,resp):
    if case["check"]:
        result = jsonpath.jsonpath(resp.json(), case["check"])[0]
        logging.info(f"3.HTTP响应断言内容：实际结果({result}) == 预期结果({case['expected']})")
        assert result == case["expected"]
    else:
        logging.info(f"3.HTTP响应断言内容：实际结果({case['expected']}) == 预期结果({resp.text})")
        assert case["expected"] in resp.text


def assert_jdbc_utils(case):
    if case["sql_check"] and case["sql_expected"]:
        with allure.step("3.数据库断言"):
            result = database_test_utils(case["sql_check"])
            logging.info(f"3.jdbc响应断言内容：实际结果({result}) == 预期结果({case['sql_expected']})")
            assert result == case["sql_expected"]


def database_test_utils(sql,index=0):
        conn = pymysql.Connect(
            host=DB_HOST,
            port=DB_PORT,
            database=DB_DATABASE,
            user=DB_USER,
            password=DB_PASSWORD,
            charset="utf8"
        )
        cur = conn.cursor()
        cur.execute(sql)
        value = cur.fetchone()
        return value[index]